import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-04
 * Time: 下午 22:02
 */
public class DBUtil {

    private static DataSource dataSource = null;

    //描述数据局库的位置
    public static DataSource getDataSource() {
        if(dataSource == null) {
            dataSource = new MysqlDataSource();
            ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/messagewall?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
            ((MysqlDataSource)dataSource).setUser("root");
            ((MysqlDataSource)dataSource).setPassword("123456");
        }

        return dataSource;
    }

    private  DBUtil() {

    }

    //建立连接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }


    //关闭连接
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {

        //推荐写成分开形式的try catch,因为在执行过程中随时都有可能异常,如果写在一起可能随机一个异常就跳出去了,下面的close就执行不到
        //反之分开写如果一个异常,不会影响其他close的执行
       if(resultSet != null) {
           try {
               resultSet.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }

       if(preparedStatement != null) {
           try {
               preparedStatement.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }

       if(connection != null) {
           try {
               connection.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
}
